//模拟服务端
let http = require('http');
let fs = require('fs');
let url = require('url');
let basePath = './vue-book/mock';
//获取轮播图 /sliders
let sliders = require('./sliders.js');

let pageSize = 5;
http.createServer((req, res)=>{
    //解决node跨域请求
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
    res.setHeader("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    if(req.method=="OPTIONS") 
        return res.end();

    let {pathname, query} = url.parse(req.url, true); // true把query转化成对象
    if(pathname === '/page'){
        let offset = parseInt(query.offset) || 0;
        read(function (books) {
            books.reverse();
            let result = books.slice(offset, pageSize+offset);
            let hasMore = true;
            if(books.length <= pageSize+offset){
                hasMore = false;
            }
            res.setHeader('Content-Type','application/json;charset=utf8');
            res.end(JSON.stringify({books: result, hasMore}));
        })
        return ;
    }
    
    if(pathname === '/sliders'){
        res.setHeader('Content-Type','application/json;charset=utf8');
        return res.end(JSON.stringify(sliders));
    }
    if(pathname === '/hot'){
        read(function (books) {//books代表所有图书
            res.setHeader('Content-Type','application/json;charset=utf8');
            let hot = books.reverse().slice(0, 6);
            res.end(JSON.stringify(hot));
        })
        return;
    }
    
    if(pathname === '/book'){//对书的增删该查
        let id = parseInt(query.id);//取出的是字符串
        switch (req.method) {
            case 'GET':
                if(!isNaN(id)){//获取单个
                    read(function (books) {
                        let book = books.find(item => item.bookId === id);
                        if(!book){//如果没找到则是undefined
                            book = {};
                        }
                        res.setHeader('Content-Type','application/json;charset=utf8');
                        res.end(JSON.stringify(book));
                    })
                }else{//获取所有
                    read(function (books) {//books代表所有图书
                        res.setHeader('Content-Type','application/json;charset=utf8');
                        res.end(JSON.stringify(books.reverse()));
                    })
                }
                break;
            case 'POST':
                let str = '';
                req.on('data', chunk => {
                    str += chunk;
                });
                req.on('end', () => {
                    let book = JSON.parse(str);
                    read(function (books) {
                        book.bookId = books.length ? books[books.length-1].bookId+1 : 1;
                        books.push(book);
                        write(books, function () {
                            res.end(JSON.stringify(book));//返回修改的数据
                        })
                    })
                });
                res.end(JSON.stringify({}));
                break;
            case 'PUT':
                if(!isNaN(id)){
                    let str = '';
                    req.on('data', chunk => {
                        str += chunk;
                    });
                    req.on('end', () => {
                        let book = JSON.parse(str);
                        read(function (books) {
                            books = books.map(item => {
                                if(item.bookId === id){//找到id相同的那一本书
                                    return book;
                                }
                                return item;//其他书正常返回即可
                            })
                            write(books, function () {
                                res.end(JSON.stringify(book));//返回修改的数据
                            })
                        })
                    });
                }
                res.end(JSON.stringify({}));
                break;
            case 'DELETE':
                read(function (books) {
                    books = books.filter(item => item.bookId !== id)
                    write(books, function () {
                        res.end(JSON.stringify({}));//删除返回空对象
                    })
                })
                break;
            default:
                break;
        }
        return;
    }
    
    // 读取一个路径
    fs.stat(basePath+pathname, function (err, states) {
        if (err) {
            res.statusCode = 404;
            res.end('Not Found')
        } else {
            // 如果是目录会报错
            if(states.isDirectory()){
                let p = require('path').join(basePath + pathname, './index.html')
                fs.createReadStream(p).pipe(res);
            } else {
                fs.createReadStream(basePath+pathname).pipe(res);
            }
        }
    })
}).listen(3000);
//vscode安装Code Runner插件后右键js，点击run code即可运行，端口号是3000
// ctrl+alt+n运行， ctrl+alt+m停止
function read(cb) {
    fs.readFile(basePath+'/book.json', 'utf8', function (err, data) {
        if(err || data.length == 0){
            cb([]);// 如果有错误或者文件没长度就是空数组
        }else{
            // 将读出来的内容转换成对象
            cb(JSON.parse(data));
        }
    })
}

function write(data, cb) {
    fs.writeFile(basePath+'/book.json', JSON.stringify(data), cb)
}

